<template>
  <div class="grid_gadget_tempalte" style="width:100%;height:100%" :id="id">
    <Portal to="right-disable" style="width:100%;height:100%;"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  class="aui-card--fill"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                   style="width:100%;height: 100%;border:0">
        <el-card shadow="never"
                 class="aui-card--fill content-card"
                 style="width:100%;height: 100%;border:0">
          <div style="width:100%;height:100%;">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName&& widgetName.trim().length>0)">

              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <div>
                <MoreMenu :slicer='slicer'
                          :fitToHeight='fitToHeight'
                          :gadgetId='id'
                          :gadgetType='gadgetInfo.com'
                          @updateQuery="query"
                          :widgetName="widgetName"
                          :businessType="gadgetInfo.businessType"
                          :id="gadgetInfo.id"
                          @showQueryModel="showQueryModel"
                          @fullScreen="fullScreen" />
              </div>
            </div>
            <div class="control-section"
                  style="margin:10px;height:100%;">
              <div v-if="isHasData">
                <div style="height:50px">
                  <div style="float:left;">
                    <div style="font-size: 12px;color: #808080;">{{gadgetSetting.heading}}</div>
                    <span style="font-size: 24px;font-weight:600" class="cursor_pointer"
                         :style="{color:compare(comDataList.currentValue)}"
                         @click="onClick">{{comDataList.currentValue}}</span>
                  </div>
                  <div style="float:right;margin-top:20px;font-size: 12px;color: #808080;">
                    <i class="cuifont icon_goal"
                       style="font-size:12px"></i>
                    {{comDataList.benchMark}}
                  </div>
                </div>
                <div :id="selfGadgetUuid"
                     :style="{'width':'100%','height':gadgetHeight-110+'px'}"></div>
              </div>
              <div v-else
                  class="gadget-no-newdata">
                    <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"  :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
              </div>
            </div>
          </div>
        </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>

    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :selectFields="selectFields"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           @saveGadgetSetting='saveGadgetSetting' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :queryId="queryId"
                  :slicer="slicer"
                  ref="drill-through"
                  :widgetName='widgetName' />
  </div>
</template>

<script>
import Vue from 'vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import { defaultGadgetSettingList } from '@/utils/data-json'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import * as Echarts from 'echarts'
import ecStat from 'echarts-stat'
import moment from 'moment'
import { getUUID } from '@/utils'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import _ from 'lodash'
export default {
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: { Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model') },
  data () {
    return {
      comDataList: [],
      selfGadgetUuid: getUUID(),
      repeatNumber: 0,
      currentTime: null,
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      dataList: [],
      loading: false,
      heightoffset: 60,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'scorecardgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'scorecardgadget' }).gadgetSetting
        }
      },
      selectFields: [],
      widgetName: '',
      linkedDatasetList: [],
      snapshotDataList: [],
      conditionFormat: [],
      // gadgetSetting: {},
      chartOption: {
        title: {},
        xAxis: {
          // show: false,
          type: 'category',
          data: []
        },
        yAxis: {
          // show: false,
          type: 'value'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}'
        },
        grid: {
          top: '10%',
          left: 0,
          right: 0,
          bottom: 0,
          width: '100%',
          height: '80%',
          containLabel: true
        },
        series: [
          {
            data: [],
            type: 'line'
          }
        ]
      },
      datesource: {},
      queryId: '',
      queryDrillthrough: {},
      widgetCode: 0
    }
  },
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    Vue['_this'] = this
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.gadgetMessageBus.$on(this.id + 'currentValue', (e) => {
      this.onClick()
    })
    this.$store.state.isWidget = false
  },
  computed: {
  },
  watch: {
    loadingStatus (val) {
      if (val) {
        this.loading = true
        this.chartDom = document.getElementById(`${this.selfGadgetUuid}`)
        if (this.chartDom) {
          let myChart = Echarts.init(this.chartDom, this.globalTheme)
          myChart.clear()
          this.$nextTick(() => {
            myChart.setOption(this.chartOption)
            myChart.resize()
          })
        }
        this.loading = false
      }
    }
  },
  updated () {
    if (document.getElementById(`${this.selfGadgetUuid}`) && document.getElementById(`${this.selfGadgetUuid}`).offsetWidth) {
      let wW = document.getElementById(`${this.selfGadgetUuid}`).offsetWidth
      let wH = document.getElementById(`${this.selfGadgetUuid}`).offsetHeight
      this.gadgetSetting.titleFontSize = (parseInt(wW / 70) + parseInt(wH / 200))<10?'10px':(parseInt(wW / 70) + parseInt(wH / 200) + 'px')
    }
  },
  methods: {
    comDataLists () {
      var fieldsName = ''
      if (this.gadgetSetting.fields && this.gadgetSetting.fields.length >= 1) {
        fieldsName = this.gadgetSetting.fields[0]
      }
      var scorecardData = {
        uid: this.widgetName + this.gadgetSetting.userName,
        userName: this.gadgetSetting.userName,
        kpi: this.widgetName,
        benchMark: this.gadgetSetting.benchMark ? this.gadgetSetting.benchMark : 30,
        currentValue: 0,
        snapShot: [],
        code: this.widgetCode
      }

      var socreDataForGantt = {
        uid: this.widgetName + this.gadgetSetting.userName,
        userName: this.gadgetSetting.userName ||'',
        userId: this.gadgetSetting.userId || '',
        headUrl: this.gadgetSetting.headUrl ||'',
        kpi: this.widgetName,
        benchMark: this.gadgetSetting.benchMark ? this.gadgetSetting.benchMark : 30,
        currentValue: 0,
        snapShot: [],
        id: this.id,
        refreshCron: this.gadgetSetting.refreshCron || '',
        code: this.widgetCode
      }

      // fill scorecardData
      if (this.dataList && this.dataList.length >= 1) {
        scorecardData.currentValue = this.formatValue(this.dataList[0][fieldsName])
        socreDataForGantt.currentValue = this.formatValue(this.dataList[0][fieldsName])
      }
      if (this.snapshotDataList && this.snapshotDataList.length > 0) {
        try {
          // fill snapshot
          scorecardData.snapShot = this.snapshotDataList.map(item => {
            return {
              date: item.snapshot_date ? this.formatDate(item.snapshot_date) : this.formatDate(new Date()),
              name: item && item[fieldsName] ? this.formatValue(item[fieldsName]) : '0',
              tooltip: '',
              iconClass: this.compare(item ? item[fieldsName] : '') ? this.compare(item ? item[fieldsName] : '') : ''
            }
          })
          socreDataForGantt.snapShot = this.snapshotDataList.map(item => {
            return {
              date: item.snapshot_date,
              name: item && item[fieldsName] ? this.formatValue(item[fieldsName]) : '0',
              tooltip: '',
              iconClass: this.compare(item ? item[fieldsName] : '') ? this.compare(item ? item[fieldsName] : '') : '',
              names: item[fieldsName],
              selectFields: this.selectFields,
              fields: this.gadgetSetting.fields[0],
              formatValue: this.formatValue,
              id: item.id || null
            }
          })
          socreDataForGantt.conditionFormat = this.conditionFormat
        } catch (error) {
          console.log('error', error)
        }
      }
      this.publishMessage('updateSharedDatalist', _.cloneDeep(socreDataForGantt))
      this.comDataList = scorecardData
      return scorecardData
    },
    updateChart (originData) {
      this.chartDom = document.getElementById(`${this.selfGadgetUuid}`)
      if (!this.chartDom) {
        setTimeout(() => {
          this.repeatNumber++
          this.updateChart(originData)
        }, 1000)
      } else if (!Array.isArray(originData) || (Array.isArray(originData) && originData.length === 0)) {
        Echarts.init(this.chartDom).dispose()
      } else {
        this.repeatNumber = 0
        this.chartOption.xAxis.data = []
        this.chartOption.series[0].data = []
        originData.forEach(item => {
          this.chartOption.xAxis.data.push(this.formatDateView(item.snapshot_date))
          this.chartOption.series[0].data.push(item[this.gadgetSetting.fields[0]])
        })
        this.chartOption.tooltip.formatter = (params) => {
          return `${params.name} <br /> ${this.formatValue(params.value)}`
        }
        this.chartOption.title.textStyle = { fontSize: this.gadgetSetting.titleFontSize || 18 }
        let myChart = Echarts.init(this.chartDom, this.globalTheme)
        if (this.gadgetSetting.showTrendLine) {
          var data = []
          originData.forEach((item, index) => {
            data.push([
              index, Number(item[this.gadgetSetting.fields[0]])
            ])
          })
          var temp = this.getRegressionChart(data, '', 'regression-chart', this.gadgetSetting.showTrendLine, 1, myChart)
          this.chartOption.series.push(temp)
        }
        myChart.setOption(this.chartOption, !!this.gadgetSetting.showTrendLine)
        // this.$erd.listenTo(this.chartDom, element => {
        //   this.$nextTick(() => {
        //     this.resized()
        //   })
        // })
      }
    },
    getRegressionChart (chartData, chartTitle, chartId, regType, regOrder, myChart) {
      let regressionDemo = ecStat.regression(regType, chartData, regOrder)
      regressionDemo.points.sort(function (a, b) {
        return a[0] - b[0]
      })

      return {
        name: 'line',
        type: 'line',
        showSymbol: false,
        lineStyle: {
          // type: "dashed",
          color: '#f00'
        },
        data: regressionDemo.points
      }
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    queryModelPreview () {
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = this.pageFromType === 'report' ? newH * this.rolHeight - this.heightoffset - 15 : newH * 20 - this.heightoffset - 15
      this.gadgetWidth = newWPx
      this.$nextTick(() => {
        if (this.chartDom) {
          let myChart = Echarts.init(this.chartDom, this.globalTheme)
          myChart.resize({
            width: this.gadgetWidth * 0.94,
            height: this.gadgetHeight - 30 * 2 - 34 - 30
          })
        }
      })
    },
    onClick () {
      let data = ''
      var pointx = ''
      pointx = this.datesource[this.queryDrillthrough.alias]
      if (!pointx && pointx !== false && pointx !== 0) {
        pointx = ' is null'
      } else {
        pointx = "='" + pointx + "'"
      }
      if (this.queryDrillthrough.dataType === 'dimension') {
        data = '"' + this.queryDrillthrough.field + '"' + pointx// "='" + this.datesource[this.queryDrillthrough.alias] + "'"
      }
      this.findOriginData(data)
    },
    formatValue (data) {
      let temp = ''
      try {
        temp = this.setFormatFunctionForChart(this.selectFields, data, this.gadgetSetting.fields[0])
      } catch (error) { }
      return temp
    },
    formatDate (date) {
      let temp = ''
      try {
        temp = moment(date).format('MM/DD/YYYY HH:mm:ss')
      } catch (error) { }
      return temp
    },
    formatDateForGantt (date) {
      let temp = ''
      try {
        temp = moment.tz(date, this.$store.state.user.timezoneId).format('MM/DD/YYYY HH:mm')
      } catch (error) { }
      return temp
    },
    formatDateView (date) {
      let temp = ''
      try {
        if (this.gadgetSetting && this.gadgetSetting.dateInterval) {
          temp = moment(date).format('MM/DD/YYYY')
          return temp
        } else {
          temp = moment.tz(date, this.$store.state.user.timezoneId).format('MM/DD/YYYY')
          return temp
        }
      } catch (error) { }
    },
    query (e) {
      if (e !== 'auto') {
        this.loading = true
      }
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      let param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      if (!param.pageId) {
        param.type = 'widget'
      }
      let params = {
        datasetKey: this.id
      }
      if (this.gadgetSetting && this.gadgetSetting.dateRange && Array.isArray(this.gadgetSetting.dateRange) && this.gadgetSetting.dateRange.length > 0 && this.gadgetSetting.dateRange[0] && this.gadgetSetting.dateRange[0] !== 'undefined') {
        params.filter = `snapshot_date >='${this.gadgetSetting.dateRange[0]}' and snapshot_date <='${this.gadgetSetting.dateRange[1]}'`
      }
      Promise.all([this.$interface.reports.getReportDataInfo(param), this.$interface.reports.postInfoForGetDataApi(params)]).then(resArray => {
        const res = resArray[0].data
        this.widgetCode = res.code
        this.snapshotDataList = resArray[1].data.data
        this.linkedDatasetList = res.datasetSync ? res.datasetSync : []
        this.heightoffset = 5
        this.gadgetHeight = this.pageFrom === 'reportLayoutFullScreen' ? window.screen.availHeight-100 :this.pageFromType === 'report' ? (this.gadgetInfo.h * this.rolHeight) - this.heightoffset - 15 : (this.gadgetInfo.h * 20) - this.heightoffset - 15
        if(this._.get(this.dataInfo,'gadgetSetting.dynamic',false)){
            this.gadgetSetting =  Object.assign({},this.dataInfo.gadgetSetting)
          }else{
            this.gadgetSetting = Object.assign({}, this._.merge(this.gadgetSetting || {}, res.config || {}))
        }
        // this.gadgetSetting.drillThroughStatus = true
        if (res.config) {
          this.conditionFormat = res.conditionFormat
        }
        // this.queryForSnapshot({ datasetKey: this.id })
        this.verifyHasData(res)

        if (res.name) {
          this.widgetName = res.name
        } else if (this.wName) {
          this.widgetName = this.wName
        } else {
          this.widgetName = this.gadgetSetting.headerTitle
        }

        this.selectFields = res.selectFields || []
        // process data

        if (res.data) {
          res.data = JSON.parse(JSON.stringify(res.data))
          this.dataList = res.data
          let tempDataList = res.data
          let objList = res.selectFields.find(item => { return item.dataType === 'dimension' })
          this.queryDrillthrough = objList || {}
          this.queryId = this.queryDrillthrough ? this.queryDrillthrough.queryId : ''

          let abc = this.gadgetSetting.fields[0]
          this.datesource[abc] = tempDataList[0][abc]
          if (this.queryDrillthrough) {
            this.datesource[this.queryDrillthrough.alias] = tempDataList[0][this.queryDrillthrough.alias]
            var tempAlias = this.datesource[this.queryDrillthrough.alias]
            if (!tempAlias) {
              this.queryDrillthrough.alias = 'dimension1'
              this.datesource[this.queryDrillthrough.alias] = tempDataList[0][this.queryDrillthrough.alias]
            }
          }
        }

        // this.updateChart(this.snapshotDataList)
        this.isGridInit = false
        if (res.data && res.data.length > 0) this.isHasData = true
        this.comDataLists()
      }).catch((error) => {
        if (this.wName) {
          this.widgetName = this.wName
        }
        Echarts.init(this.chartDom).dispose()
        this.isHasData = false
        if (error.response && error.response.status === 504) {
          this.errorStatus = '504'
          this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
        }
      }).finally(() => {
        this.currentTime = new Date()
        this.loading = false
        this.autoRefreshQuery(e)
        this.updateGadgetLoadingStatus(!this.loading)
      })
    },
    queryForSnapshot (data) {
      const param = {
        datasetKey: data.datasetKey
      }
      var _self = this
      if (_self.gadgetSetting && _self.gadgetSetting.dateRange && Array.isArray(_self.gadgetSetting.dateRange) && _self.gadgetSetting.dateRange.length > 0 && _self.gadgetSetting.dateRange[0] && _self.gadgetSetting.dateRange[0] !== 'undefined') {
        param.filter = `snapshot_date >='${_self.gadgetSetting.dateRange[0]}' and snapshot_date <='${_self.gadgetSetting.dateRange[1]}'`
      }
      this.$interface.reports.postInfoForGetDataApi(param)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            // return this.$message.error(res.msg)
          }
          this.snapshotDataList = res.data
          this.updateChart(res.data)
        })
    },
    compare (data) {
      let temp = ''
      var _self = this
      var arr = _self.conditionFormat
      var res = arr.filter(item => {
        if (item.dataForm.filters.rules.length !== 0) {
          return item.dataForm.filters.rules[0].key === _self.gadgetSetting.fields[0]
        }
      })
      if (data && res && res.length > 0) {
        res.reverse().forEach(it => {
          if (it) {
            if (data === null) return temp // [it.dataForm.filters.rules[0].key]
            // eslint-disable-next-line
            var val = data.toString().replace(/[\$\,]/g, '')//[it.dataForm.filters.rules[0].key]
            if (val.includes('%')) {
              // eslint-disable-next-line
              val = Number(val.replace(/%/g, '')) / 100
            } else if (val.indexOf('k') > -1) {
              // eslint-disable-next-line
              val = Number(val.replace(/k/g, '')) * 1000
            }
            if (it.dataForm.filters.rules[0].opt === '==' || it.dataForm.filters.rules[0].opt === '!=') {
              // eslint-disable-next-line
              if (it && eval((val).toString() + it.dataForm.filters.rules[0].opt + (it.dataForm.filters.rules[0].value).toString())) {
                temp = it.textColor
              }
            } else {
              // eslint-disable-next-line
              if (it && eval(Number(val) + it.dataForm.filters.rules[0].opt + Number(it.dataForm.filters.rules[0].value))) {
                temp = it.textColor
              }
            }
          }
        })
      }
      return temp
    },
    destroyed () {
      delete Vue['_this']
    },
    remove () {
      this.close()
      if (this.drop.parentNode) {
        this.drop.parentNode.removeChild(this.drop)
      }
    }
  },
  destroyed () {
    this.gadgetMessageBus.$off(this.id + 'currentValue')
  }
}
</script>
<style lang="scss" scoped>
.content-card {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 45%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.grid_gadget_tempalte ::v-deep .showToobar .e-grid .e-toolbar {
  display: none;
}
.grid_gadget_tempalte ::v-deep .e-grid .e-summarycell {
  font-size: 13px;
  background-color: #f6f6f6;
  border-color: #e0e0e0;
  color: rgba(0, 0, 0, 0.54);
  font-weight: normal;
}
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}

.header {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
}

.e-grid ::v-deep .e-filter-popup {
  max-height: 300px !important;
  overflow-y: auto;
}

.e-grid ::v-deep .e-checkboxlist {
  height: auto !important;
  overflow-y: visible !important;
}
</style>
